package com.neiquan.weiguan.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.neiquan.weiguan.R;
import com.neiquan.weiguan.activity.base.BaseActivity;
import com.neiquan.weiguan.colorful.Colorful;
import com.neiquan.weiguan.fragment.ArticleFragment;
import com.neiquan.weiguan.fragment.GameFragment;
import com.neiquan.weiguan.fragment.HomeTabFragment;
import com.neiquan.weiguan.fragment.MeFragment;
import com.neiquan.weiguan.fragment.VideoListFragment;
import com.neiquan.weiguan.utils.Constant;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {


    @InjectView(R.id.lin_homepage)
    LinearLayout lin_homepage;
    @InjectView(R.id.lin_video)
    LinearLayout lin_video;
    @InjectView(R.id.lin_game)
    LinearLayout lin_game;
    @InjectView(R.id.lin_article)
    LinearLayout lin_article;
    @InjectView(R.id.lin_me)
    LinearLayout lin_me;

    private HomeTabFragment homeTabFragment;
    private VideoListFragment videoListFragment;
    private GameFragment gameFragment;
    private ArticleFragment articleFragment;
    private MeFragment meFragment;
    private Fragment fragments[];
    private int currentTabIndex;
    private List<LinearLayout> mLayViewList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) {
            // 防止被移除后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
            // 三个fragment里加的判断同理
            //   MyApplication.getInstance().logout(null);
            finish();
            //startActivity(new Intent(this, LoginActivity.class));
            return;
        } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
            // 防止被T后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
            // 三个fragment里加的判断同理
            finish();
            //startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        //    MobclickAgent.updateOnlineConfig(this);

        init(savedInstanceState);
        mLayViewList.add(lin_homepage);
        mLayViewList.add(lin_video);
        mLayViewList.add(lin_game);
        mLayViewList.add(lin_article);
        mLayViewList.add(lin_me);
    }

    @Override
    protected void onPause() {
        videoListFragment.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        homeTabFragment.onResume();
        super.onResume();
    }

    protected void init(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            homeTabFragment = new HomeTabFragment();
            videoListFragment = new VideoListFragment();
            gameFragment = new GameFragment();
            articleFragment = new ArticleFragment();
            meFragment = new MeFragment();
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, homeTabFragment, HomeTabFragment.class.getSimpleName())
                    .add(R.id.fragment_container, videoListFragment, VideoListFragment.class.getSimpleName())
                    .add(R.id.fragment_container, gameFragment, GameFragment.class.getSimpleName())
                    .add(R.id.fragment_container, articleFragment, ArticleFragment.class.getSimpleName())
                    .add(R.id.fragment_container, meFragment, MeFragment.class.getSimpleName())
                    .hide(videoListFragment)
                    .hide(gameFragment)
                    .hide(articleFragment)
                    .hide(meFragment)
                    .show(homeTabFragment)
                    .commit();
        } else {
            currentTabIndex = savedInstanceState.getInt("index");// 取出来当前第几个fragment
            FragmentManager fmg = getSupportFragmentManager();
            homeTabFragment = (HomeTabFragment) fmg.findFragmentByTag(HomeTabFragment.class.getSimpleName());
            videoListFragment = (VideoListFragment) fmg.findFragmentByTag(VideoListFragment.class.getSimpleName());
            gameFragment = (GameFragment) fmg.findFragmentByTag(GameFragment.class.getSimpleName());
            articleFragment = (ArticleFragment) fmg.findFragmentByTag(ArticleFragment.class.getSimpleName());
            meFragment = (MeFragment) fmg.findFragmentByTag(MeFragment.class.getSimpleName());
            fragments = new Fragment[]{homeTabFragment, videoListFragment, gameFragment, articleFragment, meFragment};
            fmg.beginTransaction()
                    .hide(homeTabFragment)
                    .hide(videoListFragment)
                    .hide(gameFragment)
                    .hide(articleFragment)
                    .hide(meFragment)
                    .show(fragments[currentTabIndex])
                    .commit(); // 显示以前报错的fragment
            // 底部换过来
            replaceFragmet(0, currentTabIndex);
        }
        fragments = new Fragment[]{homeTabFragment, videoListFragment, gameFragment, articleFragment, meFragment};
        updateTab(0);
        setupColorful();
    }


    /**
     * 切换fragment
     *
     * @param oldIndex 当前的fragment
     * @param newIndex 切换到第几个frament
     */
    private void replaceFragmet(int oldIndex, int newIndex) {
        if (newIndex != oldIndex) {
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            trx.hide(fragments[oldIndex]);
            if (fragments[oldIndex] instanceof VideoListFragment) {
                fragments[oldIndex].onPause();
            }
            trx.show(fragments[newIndex]).commit();
            currentTabIndex = newIndex;
            updateTab(currentTabIndex);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constant.ONACTIVITYRESULT_CHANNEL:
                homeTabFragment.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    @Override
    protected void setupColorful() {
        colorful = new Colorful.Builder(this)
                .backgroundColor(R.id.fragment_container, R.attr.root_view_bg)
                .backgroundColor(R.id.lin_main_tab, R.attr.title_bottom_view_bg)
                .create();
    }


    private long clickTime = 0; //记录第一次点击的时间

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - clickTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次后退键退出程序",
                        Toast.LENGTH_SHORT).show();
                clickTime = System.currentTimeMillis();
            } else {
                this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @OnClick({R.id.lin_homepage, R.id.lin_video, R.id.lin_game, R.id.lin_article, R.id.lin_me})
    public void onClick(View view) {
        int index = 0;
        switch (view.getId()) {
            case R.id.lin_homepage:
                index = 0;
                break;
            case R.id.lin_video:
                index = 1;
                break;
            case R.id.lin_game:
                index = 2;
                break;
            case R.id.lin_article:
                index = 3;
                break;
            case R.id.lin_me:
                index = 4;
                break;

        }
        replaceFragmet(currentTabIndex, index);
    }

    private void updateTab(int current) {
        int hcolor = getResources().getColor(R.color.home_tabhost_textcolor_select);
        int wcolor = getResources().getColor(R.color.home_tabhost_textcolor);
        for (int i = 0; i < mLayViewList.size(); i++) {
            LinearLayout linearLayout = mLayViewList.get(i);
            ImageView imageView = (ImageView) linearLayout.getChildAt(0);
            TextView textView = (TextView) linearLayout.getChildAt(1);
            if (current == i) {
                switch (i) {
                    case 0:
                        imageView.setImageResource(R.drawable.home_page_select);
                        break;
                    case 1:
                        imageView.setImageResource(R.drawable.video_select);
                        break;
                    case 2:
                        imageView.setImageResource(R.drawable.game);
                        break;
                    case 3:
                        imageView.setImageResource(R.drawable.article_select);
                        break;
                    case 4:
                        imageView.setImageResource(R.drawable.me_select);
                        break;
                }
                textView.setTextColor(hcolor);
            } else {
                switch (i) {
                    case 0:
                        imageView.setImageResource(R.drawable.home_page);
                        break;
                    case 1:
                        imageView.setImageResource(R.drawable.video);
                        break;
                    case 2:
                        imageView.setImageResource(R.drawable.game);
                        break;
                    case 3:
                        imageView.setImageResource(R.drawable.article);
                        break;
                    case 4:
                        imageView.setImageResource(R.drawable.me);
                        break;
                }
                textView.setTextColor(wcolor);
            }
        }
    }
}
